package com.sunshine.lnuplus.internet

import com.sunshine.lnuplus.callback.LoadDataCallBack
import com.sunshine.lnuplus.service.LoadFunctionService
import okhttp3.*
import org.json.JSONException
import org.jsoup.Jsoup
import java.io.IOException

class LoadFunction(
    private val service: LoadFunctionService,
    private val functionList: ArrayList<ArrayList<String>>,
    private var callBack: LoadDataCallBack
) {

    init {
        loadFunction()
    }

    private fun loadFunction() {
        val url = "http://www.iyuji.cn/iyuji/s/VUlpZG1WZ3A2alo2OWtxZThadHU2QT09/1583232976909121"
        val okHttpClient = OkHttpClient()
        val request = Request.Builder().url(url).build()
        val call = okHttpClient.newCall(request)
        call.enqueue(object : Callback {
            override fun onFailure(call: Call, e: IOException) {
                service.stopSelf()
            }

            @Throws(IOException::class)
            override fun onResponse(call: Call, response: Response) {
                resolveFunction(response.body!!.string())
            }
        })
    }

    private fun resolveFunction(functionData: String) {
        try {
            val document = Jsoup.parse(functionData)
            val elements = document.select("p")
            val functionStrings = elements.toString().replace("<p>", "").replace("</p>", "").split("#")
            functionStrings.forEach {
                val function = ArrayList<String>()
                it.split("*").forEach{torm ->
                    function.add(torm)
                }
                functionList.add(function)
            }
            callBack.onSuccess()
        } catch (e: JSONException) {
            e.printStackTrace()
        }
    }
}